import { defineStore } from 'pinia'
import { UserState } from '../types'

import { getCurrentUserAuthCode } from '@/api/login'

const defaultAvatar = 'http://static-erp.oss-cn-shenzhen.aliyuncs.com/yfni/test/161709313326232f707.png'

const useUserStore = defineStore('user-info', {
  state: () => {
    return {
      avatar: defaultAvatar,
      admin: false,
      skin: '',
      companyId: '',
      companyName: '',
      companyShortName: '',
      deptId: '',
      deptName: '',
      userId: '',
      userName: '',
      token: '',
      lang: localStorage.getItem('lang') || 'zh',
      authCodeMap: {},
      isLoadAuth: false,
      jumpFlag: 'noJump',
    }
  },
  actions: {
    setJumpFlag(address: string) {
      this.jumpFlag = address
    },

    // 获取用户基础信息
    async initUser(token: string, userInfo: UserState) {
      return new Promise<UserState>(async (resolve, reject) => {
        if (!token || !userInfo.id) {
          reject(false)
        }

        const firstLoginInfo = window.localStorage.getItem('first-login-info')
        if (!firstLoginInfo) {
          window.localStorage.setItem('first-login-info', JSON.stringify(userInfo))
        }
        this.avatar = userInfo.headerImage || defaultAvatar
        this.admin = userInfo.admin
        this.companyId = userInfo.companyId
        this.companyName = userInfo.companyName
        this.companyShortName = userInfo.companyShortName
        this.deptId = userInfo.deptId
        this.deptName = userInfo.deptName
        this.userId = userInfo.id
        this.userName = userInfo.userName
        this.token = token
        resolve(userInfo)
        reject(false)
      })
    },
    // 获取用户授权信息
    async getUserAuthCode() {
      // 存在授权列表不处理
      if (this.isLoadAuth) {
        return
      }
      const res: any = await getCurrentUserAuthCode()
      if (res?.data) {
        this.isLoadAuth = true
        this.admin = res.data.admin
        const authCodeMap: any = {}
        const authCodeList = res.data?.authCodeList || []
        authCodeList.forEach((code: string) => {
          authCodeMap[code] = true
        })
        this.authCodeMap = authCodeMap
      } else {
        this.isLoadAuth = false
      }
    },
    setLang(payload: string) {
      this.lang = payload
    },
    logout() {
      return new Promise<void>((resolve) => {
        this.$reset()
        localStorage.removeItem('user-info')
        localStorage.removeItem('visited-routes')
        localStorage.removeItem('first-login-info')
        sessionStorage.clear()
        resolve()
      })
    },
  },
  presist: {
    enable: true,
    resetToState: true,
    option: {
      exclude: ['lang', 'authCodeMap', 'isLoadAuth', 'jumpFlag'],
    },
  },
})

export default useUserStore
